import tkinter as tk

class PixelGrid(tk.Canvas): #继承tk模块中Canvas类
    """创建网格类（继承于tk中的网格类）"""
    def __init__(self, master,grid_size=20,cell_size=25,
                 padding=50,*args,**kwargs):
        #引用父类中的画布
        super().__init__(master,*args,**kwargs)
        #初始网格属性
        self.grid_size = grid_size    #网格大小
        self.cell_size = cell_size    #单元格大小
        self.padding = padding        #边距大小
        #初始化白色网格矩阵
        self.pixels = [
            ["#FFFFFF"for _ in range(self.grid_size)]
             for _ in range(self.grid_size)
        ]
        #设置背景颜色
        self.config(bg="white")    #设置画布背景颜色
        self.current_color = "#FF0000"    #当前画笔颜色：红色
        self.draw_grid()    # 绘制网格（初始化）
        self.bind("<Button-1>", self.on_click)    #颜色选择
        self.bind("<B1-Motion>", self.on_drag)    #画笔移动
    def on_click(self,event):
        """处理点击过程"""
        self.handle_paint(event)
    def on_drag(self,event):
        """处理拖拽事件"""
        self.handle_paint(event)
    def draw_grid(self):
        """绘制网格"""
        self.delete("all")#清除画布
        for r in range(self.grid_size):
            for c in range(self.grid_size):
                x1=self.padding+c*self.cell_size
                y1=self.padding+r*self.cell_size
                x2= x1+self.cell_size
                y2= y1+self.cell_size
                self.create_rectangle(x1, y1, x2, y2,
                fill=self.pixels[r][c], outline="#CCCCCC")

    def handle_paint(self, event):
        """处理绘制事件"""
        c = (event.x-self.padding)//self.cell_size
        r = (event.y-self.padding)//self.cell_size
        #检查点击的位置是否在网格之内
        if 0<=r<self.grid_size and 0<=c<self.grid_size:
            self.pixels[r][c] = self.current_color
            x1 = self.padding + c*self.cell_size
            y1 = self.padding + r*self.cell_size
            x2 = x1 + self.cell_size
            y2 = y1 + self.cell_size
            self.create_rectangle(x1, y1, x2, y2,
            fill=self.current_color, outline="#CCCCCC")
    def clear_grid(self):
        """清空网格"""
        self.pixels = [
            ["#FFFFFF"for _ in range(self.grid_size)]
        ]
        self.draw_grid()
    def set_color(self, color):
        """设置当前画笔颜色"""
        self.current_color = color